from typing import List, Optional, Dict, Any
from .task import Task, Priority, TaskStatus


class TaskManager:
    """任务管理器"""
    
    def __init__(self):
        self._tasks: Dict[str, Task] = {}
    
    def add_task(self, title: str, description: str = "", priority: Priority = Priority.MEDIUM) -> Task:
        """添加新任务"""
        task = Task(title, description, priority)
        self._tasks[task.id] = task
        return task
    
    def get_task(self, task_id: str) -> Optional[Task]:
        """根据ID获取任务"""
        return self._tasks.get(task_id)
    
    def update_task(self, task_id: str, title: str = None, description: str = None, priority: Priority = None) -> bool:
        """更新任务"""
        task = self.get_task(task_id)
        if task:
            task.update(title, description, priority)
            return True
        return False
    
    def delete_task(self, task_id: str) -> bool:
        """删除任务"""
        if task_id in self._tasks:
            del self._tasks[task_id]
            return True
        return False
    
    def toggle_task_status(self, task_id: str) -> bool:
        """切换任务状态"""
        task = self.get_task(task_id)
        if task:
            if task.status == TaskStatus.PENDING:
                task.mark_completed()
            else:
                task.mark_pending()
            return True
        return False
    
    def get_all_tasks(self) -> List[Task]:
        """获取所有任务"""
        return list(self._tasks.values())
    
    def get_tasks_by_status(self, status: TaskStatus) -> List[Task]:
        """根据状态获取任务"""
        return [task for task in self._tasks.values() if task.status == status]
    
    def get_tasks_by_priority(self, priority: Priority) -> List[Task]:
        """根据优先级获取任务"""
        return [task for task in self._tasks.values() if task.priority == priority]
    
    def get_pending_tasks(self) -> List[Task]:
        """获取待完成任务"""
        return self.get_tasks_by_status(TaskStatus.PENDING)
    
    def get_completed_tasks(self) -> List[Task]:
        """获取已完成任务"""
        return self.get_tasks_by_status(TaskStatus.COMPLETED)
    
    def get_task_count(self) -> Dict[str, int]:
        """获取任务统计信息"""
        all_tasks = self.get_all_tasks()
        pending_tasks = self.get_pending_tasks()
        completed_tasks = self.get_completed_tasks()
        
        return {
            'total': len(all_tasks),
            'pending': len(pending_tasks),
            'completed': len(completed_tasks)
        }
    
    def clear_completed_tasks(self) -> int:
        """清除所有已完成任务"""
        completed_tasks = self.get_completed_tasks()
        count = 0
        for task in completed_tasks:
            if self.delete_task(task.id):
                count += 1
        return count
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'tasks': [task.to_dict() for task in self._tasks.values()]
        }
    
    def from_dict(self, data: Dict[str, Any]):
        """从字典加载数据"""
        self._tasks.clear()
        if 'tasks' in data:
            for task_data in data['tasks']:
                task = Task.from_dict(task_data)
                self._tasks[task.id] = task
    
    def __len__(self) -> int:
        return len(self._tasks)